package cn.com.pureAppApi.exception;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import cn.com.pureAppApi.interceptor.HeaderEnum;

/**
 * QQ讨论群:76989293
 * @email 2696701142@qq.com
 * @date 2018-06-12 16:51:48
 */
@ControllerAdvice
public class WebControllerAdvice {
	final static Log logger = LogFactory.getLog(WebControllerAdvice.class);

	@ExceptionHandler(Exception.class)  
    @ResponseStatus(HttpStatus.OK) 
    public Object exception(HttpServletRequest request, HttpServletResponse response, Exception e) {
		response.setCharacterEncoding("UTF-8");
		ResponseException resExc = null;
		if(e instanceof ResponseException){
			resExc = (ResponseException) e;
            logger.warn(String.format("逻辑异常,发送[%s]通知前端",resExc.getMessage()));
            response.setIntHeader(HeaderEnum.CODE.getKey(),resExc.getCode());
			response.setHeader(HeaderEnum.MESSAGE.getKey(),enCodeMessage(resExc.getMsg()));
		}else if(e.getCause() instanceof ResponseException){
			resExc = (ResponseException) e.getCause();
            logger.warn(String.format("逻辑异常,发送[%s]通知前端",resExc.getMessage()));
            response.setIntHeader(HeaderEnum.CODE.getKey(),resExc.getCode());
			response.setHeader(HeaderEnum.MESSAGE.getKey(),enCodeMessage(resExc.getMsg()));
		}else{
		    logger.error(String.format("请求异常,后台错误[%s]",e.getMessage()),e);
			response.setIntHeader(HeaderEnum.CODE.getKey(), ResponseCodeEnum.OTHER.getCode());
			response.setHeader(HeaderEnum.MESSAGE.getKey(), enCodeMessage(ResponseCodeEnum.OTHER.getMessage()));
		}
//		if(handlerMethod.getMethod().getReturnType().equals(ModelAndView.class)){
//			return new ModelAndView("error");
//		}else{
		if(resExc!=null&&resExc.getCode()==99999){
			return new ResponseEntity<Object>(resExc.getCodeEnum(),HttpStatus.OK);
		}		
		return new ResponseEntity<Object>(HttpStatus.OK);

//		}
    }
	
    private String enCodeMessage(String msg){
        try {
            return URLEncoder.encode(msg, "UTF-8");
        } catch (UnsupportedEncodingException e) {
           logger.error("异常信息enCode异常",e);
        }
        return "error";
    }
}
